﻿/**************************************************************************************************************
 * Class name:  ConfigurationManagerHelper.cs
 * Description: 提供对 Web 应用程序配置文件的访问协助
 * Author:      Ju2ender
 * Create:      2012-10-26 Friday 10:23:44
 * Update:      2012-10-26 Friday 10:23:44
 **************************************************************************************************************/

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Web.Configuration;

namespace DearLee.Toolkit.Config {

  /// <summary>
  /// 提供对 Web 应用程序配置文件的访问协助
  /// </summary>
  public class WebConfigurationManagerHelper {

    /// <summary>
    /// 将值写入指定配置文件节
    /// </summary>
    /// <param name="key">键</param>
    /// <param name="value">值</param>
    public static void SetValue(string key, string value) {

      Configuration config = null;

      config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

      if (config.AppSettings.Settings[key] == null) {
        config.AppSettings.Settings.Add(key, value);
      }
      else {
        config.AppSettings.Settings[key].Value = value;
      }

      config.Save(ConfigurationSaveMode.Modified);
      ConfigurationManager.RefreshSection("appSettings");
    }

    /// <summary>
    /// 读取指定配置文件节中的值
    /// </summary>
    /// <param name="key">键</param>
    /// <returns>值</returns>
    public static string GetValue(string key) {

      Configuration config = null;
      string value = string.Empty;

      config = WebConfigurationManager.OpenWebConfiguration("~");

      if (config.AppSettings.Settings[key] != null) {
        value = config.AppSettings.Settings[key].Value;
      }

      return value;
    }
  }
}
